<template>
  <div class="borrow-container">
    <el-row :gutter="20">
      <el-col :span="16">
        <el-card class="main-card">
          <template #header>
            <div class="card-header">
              <span>借阅操作台</span>
              <div class="header-right">
                <el-tag v-if="currentReader" type="success"
                  >当前用户：{{ currentReader.name }}</el-tag
                >
                <el-button
                  v-if="!currentReader"
                  type="warning"
                  size="small"
                  @click="backToLogin"
                >
                  <el-icon><Back /></el-icon>
                  返回登录
                </el-button>
              </div>
            </div>
          </template>

          <div v-if="!currentReader" class="scan-reader">
            <div v-if="!startScanning" class="start-scan-button">
              <el-button
                type="primary"
                size="large"
                @click="startScanningReader"
              >
                <el-icon><VideoCameraFilled /></el-icon>
                开始扫描借阅证
              </el-button>
            </div>
            <div v-else class="scan-area">
              <SteamBarcodeReader
                @decode="handleReaderScan"
                :paused="!startScanning"
              />
              <el-button class="cancel-scan" @click="cancelScanningReader"
                >取消扫描</el-button
              >
            </div>
          </div>
          <!-- 借阅证扫描完成后 -->
          <div v-else class="operation-area">
            <div class="action-buttons" v-if="!currentOperation">
              <el-button type="primary" size="large" @click="startBorrow"
                >借阅图书</el-button
              >
              <el-button type="success" size="large" @click="startReturn"
                >归还图书</el-button
              >
              <el-button
                type="danger"
                size="large"
                @click="handleBack"
                class="back-button"
                >返回 ({{ timeLeft }}秒)</el-button
              >
            </div>

            <!-- 扫描图书IBSN条形码 -->
            <div v-else class="scan-book">
              <div class="scan-area">
                <SteamBarcodeReader
                  @decode="handleBookScan"
                  :paused="!isBookScanning"
                />
              </div>
              <div class="scanned-books">
                <h4>已扫描图书</h4>
                <el-table :data="scannedBooks" style="width: 100%">
                  <el-table-column prop="title" label="书名" />
                  <el-table-column prop="author" label="作者" width="120" />
                  <el-table-column prop="location" label="位置" width="120" />
                  <el-table-column fixed="right" label="操作" width="100">
                    <template #default="scope">
                      <el-button
                        type="danger"
                        :icon="Delete"
                        circle
                        @click="removeBook(scope.$index)"
                        class="delete-btn"
                      />
                    </template>
                  </el-table-column>
                </el-table>
                <div class="action-footer">
                  <el-button type="primary" @click="handleConfirm"
                    >确认{{
                      currentOperation === "borrow" ? "借阅" : "归还"
                    }}</el-button
                  >
                  <el-button @click="cancelOperation">取消</el-button>
                </div>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="8">
        <el-card v-if="currentReader" class="reader-info">
          <template #header>
            <div class="card-header">
              <span>读者信息</span>
            </div>
          </template>
          <div class="info-content">
            <p><label>姓名：</label>{{ currentReader.name }}</p>
            <p><label>学号：</label>{{ currentReader.studentId }}</p>
            <p>
              <label>已借：</label>{{ currentReader.books.length }}/{{
                maxBorrow
              }}本
            </p>
            <el-divider />
            <h4>当前借阅</h4>
            <el-table :data="currentReader.books" style="width: 100%">
              <el-table-column prop="title" label="书名" />
              <el-table-column prop="due_time" label="应还日期" width="120">
                <template #default="scope">
                  {{
                    new Date(scope.row.due_time).toLocaleDateString("zh-CN", {
                      year: "numeric",
                      month: "long",
                      day: "numeric",
                    })
                  }}
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <FloatingAI />
    <welcomeAudioTip ref="welcomeAudio" :audiourl="'/audio/welcome.mp3'" />
  </div>
</template>
  
  <script setup>
import { ref, onUnmounted, watch } from "vue";
import { ElMessage } from "element-plus";
import SteamBarcodeReader from "@/components/steambarcodereader.vue";
import {
  getUserBorrowInfoByCardno,
  getBookInfoByISBN,
  borrowBook,
  returnBook,
} from "@/api/index"; // 修改导入方式
import { useRouter } from "vue-router";
import FloatingAI from "@/components/ai/FloatingAI.vue";
import welcomeAudioTip from "@/components/welcomeAudioTip.vue";

const currentReader = ref(null);
const currentOperation = ref("");
const scannedBooks = ref([]);
const maxBorrow = 5;
// 读者证扫描对象
const readerCard = ref(null);
const startScanning = ref(false);
const isBookScanning = ref(false); // 添加图书扫描状态控制
// @/assets/audio.mp3
const audioUrl = ref(
  new URL("@/assets/media/initusercardno.wav", import.meta.url).href
);

// 添加计时器相关的状态
const timeLeft = ref(90);
let timer = null;

// 重置计时器
const resetTimer = () => {
  if (timer) clearInterval(timer);
  timeLeft.value = 90;
  startTimer();
};

// 开始计时器
const startTimer = () => {
  timer = setInterval(() => {
    if (timeLeft.value > 0) {
      timeLeft.value--;
    } else {
      handleBack();
    }
  }, 1000);
};

// 监听用户操作，重置计时器
const resetOnUserAction = () => {
  if (currentReader.value) {
    resetTimer();
  }
};

// 监听 currentReader 变化
watch(currentReader, (newValue) => {
  if (newValue) {
    resetTimer();
  } else if (timer) {
    clearInterval(timer);
  }
});

// 组件卸载时清理计时器
onUnmounted(() => {
  if (timer) clearInterval(timer);
});

// 修改用户数据映射函数
const mapUserData = (data) => ({
  id: data.user_id,
  name: data.real_name,
  studentId: data.studentno,
  books:
    data.borrowingBooks?.map((book) => ({
      title: book.title,
      due_time: book.due_time,
      book_id: book.book_id,
    })) || [],
  avatar: data.student_img,
});

// 处理读者证扫描
const handleReaderScan = async (result) => {
  try {
    const cardno = result;
    readerCard.value = { cardno }; // 修正readerCard的赋值
    const response = await getUserBorrowInfoByCardno(readerCard.value);
    if (response.code === 200) {
      currentReader.value = mapUserData(response.data);
      ElMessage.success(`欢迎，${currentReader.value.name}`);
    } else {
      ElMessage.error(response.msg || "读者信息获取失败");
    }
  } catch (error) {
    console.error("获取读者信息错误:", error);
    ElMessage.error("读者信息获取失败");
  }
};

// 处理图书扫描
const handleBookScan = async (result) => {
  if (!currentOperation.value) return;

  try {
    // 检查是否重复扫描
    if (scannedBooks.value.some((book) => book.isbn === result)) {
      ElMessage.warning("该图书已扫描");
      return;
    }

    // 构建请求参数，增加operation和user_id
    const params = {
      isbn: result,
      operation: currentOperation.value,
      user_id: currentReader.value.id,
    };

    // 获取图书信息
    const response = await getBookInfoByISBN(params);

    // 处理不同的响应状态
    if (response.code === 200) {
      // 正常情况：可以借阅或归还
      if (currentOperation.value === "borrow") {
        if (currentReader.value.books.length >= maxBorrow) {
          ElMessage.warning("已达最大借阅数量");
          return;
        }
      }

      const bookInfo = {
        title: response.data.title,
        author: response.data.author,
        location: response.data.location,
        book_id: response.data.book_id,
        isbn: result,
      };

      scannedBooks.value.push(bookInfo);
      ElMessage.success(`成功扫描：${bookInfo.title}`);
    } else if (response.code === 230) {
      // 借阅时：用户已借阅过该书籍
      ElMessage.warning(response.msg || "用户已借阅过，请换一本书");
    } else if (response.code === 240) {
      // 归还时：用户未借阅该书籍
      ElMessage.warning(response.msg || "当前用户未借阅该书籍");
    } else {
      ElMessage.error(response.msg || "图书信息获取失败");
    }
  } catch (error) {
    console.error("获取图书信息错误:", error);
    ElMessage.error("图书信息获取失败");
  }
};

//扫描图书前，播放音频提示
const playBookAudio = () => {
  //更换音频scanbookisbn.wav
  audioUrl.value = new URL(
    "@/assets/media/scanbookisbn.wav",
    import.meta.url
  ).href;
  const audio = new Audio(audioUrl.value);
  audio.play().catch((error) => {
    console.error("播放音频失败:", error);
  });
};

// 借阅书籍达到上限borrowmax.wav
const playMaxBorrowAudio = () => {
  audioUrl.value = new URL(
    "@/assets/media/borrowmax.wav",
    import.meta.url
  ).href;
  const audio = new Audio(audioUrl.value);
  audio.play().catch((error) => {
    console.error("播放音频失败:", error);
  });
};

//开始借书
const startBorrow = () => {
  if (currentReader.value.books.length >= maxBorrow) {
    ElMessage.warning("已达最大借阅数量");
    playMaxBorrowAudio(); // 播放音频提示
    return;
  }
  currentOperation.value = "borrow";
  isBookScanning.value = true; // 开始扫描图书
  playBookAudio(); // 播放音频提示
};

//开始还书
const startReturn = () => {
  currentOperation.value = "return";
  isBookScanning.value = true; // 开始扫描图书
  playBookAudio(); // 播放音频提示
};

const cancelOperation = () => {
  currentOperation.value = "";
  scannedBooks.value = [];
  isBookScanning.value = false; // 停止扫描图书
};

const removeBook = (index) => {
  scannedBooks.value.splice(index, 1);
};

// 确认借阅或归还成功后提示音
const playBorrowSuccessAudio = () => {
  audioUrl.value = new URL(
    "@/assets/media/borrowsuccess.wav",
    import.meta.url
  ).href;
  const audio = new Audio(audioUrl.value);
  audio.play().catch((error) => {
    console.error("播放音频失败:", error);
  });
};

// 确认归还成功提示音returnsuccess.wav
const playReturnSuccessAudio = () => {
  audioUrl.value = new URL(
    "@/assets/media/returnsuccess.wav",
    import.meta.url
  ).href;
  const audio = new Audio(audioUrl.value);
  audio.play().catch((error) => {
    console.error("播放音频失败:", error);
  });
};

// 确认借阅或归还操作
const handleConfirm = async () => {
  if (scannedBooks.value.length === 0) {
    ElMessage.warning("请先扫描图书");
    return;
  }

  try {
    // 准备请求参数
    const params = {
      user_id: currentReader.value.id,
      books: scannedBooks.value.map((book) => book.book_id),
    };

    // 根据当前操作调用相应的API
    const response = await (currentOperation.value === "borrow"
      ? borrowBook(params)
      : returnBook(params));

    if (response.code === 200) {
      // 播放相应的成功提示音
      if (currentOperation.value === "borrow") {
        playBorrowSuccessAudio();
      } else {
        playReturnSuccessAudio();
      }

      ElMessage.success(
        `${currentOperation.value === "borrow" ? "借阅" : "归还"}成功`
      );
      // 刷新读者信息
      const readerResponse = await getUserBorrowInfoByCardno(readerCard.value);
      if (readerResponse.code === 200) {
        currentReader.value = mapUserData(readerResponse.data);
      }
      isBookScanning.value = false;
      cancelOperation();
    } else {
      ElMessage.error(
        response.msg ||
          `${currentOperation.value === "borrow" ? "借阅" : "归还"}失败`
      );
    }
  } catch (error) {
    console.error("操作失败:", error);
    ElMessage.error(
      `${currentOperation.value === "borrow" ? "借阅" : "归还"}失败`
    );
  }
};

//点击开始扫描借阅证按钮后，播放音频提示
const playAudio = () => {
  const audio = new Audio(audioUrl.value);
  audio.play().catch((error) => {
    console.error("播放音频失败:", error);
  });
};
//点击开始扫描借阅证
const startScanningReader = () => {
  startScanning.value = true;
  playAudio();
};

//取消扫描
const cancelScanningReader = () => {
  startScanning.value = false;
};

const handleBack = () => {
  if (timer) clearInterval(timer);
  currentReader.value = null;
  readerCard.value = null;
  startScanning.value = false;
  currentOperation.value = "";
  scannedBooks.value = [];
};

const router = useRouter();

const backToLogin = () => {
  router.push("/login");
};

// 添加用户交互事件监听
const userActions = ["click", "mousemove", "keypress"];
userActions.forEach((event) => {
  document.addEventListener(event, resetOnUserAction);
});
</script>
  
  <style scoped>
.borrow-container {
  padding: 20px;
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #e4e8eb 100%);
}

.main-card,
.reader-info {
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  border-radius: 12px;
  transition: all 0.3s ease;
}

.main-card:hover,
.reader-info:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 24px rgba(0, 0, 0, 0.12);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 0;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 12px;
}

.card-header span {
  font-size: 18px;
  font-weight: 600;
  color: #2c3e50;
}

.scan-area {
  height: 330px;
  background: linear-gradient(145deg, #ffffff 0%, #f0f2f5 100%);
  border-radius: 12px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  overflow: hidden;
  border: 2px dashed #e0e3e9;
  position: relative;
}

.scan-area :deep(video) {
  height: 250px;
  object-fit: cover;
  border-radius: 8px;
}

.action-buttons {
  display: flex;
  justify-content: center;
  gap: 24px;
  padding: 40px 0;
}

.action-buttons .el-button {
  min-width: 140px;
  height: 48px;
  font-size: 16px;
  border-radius: 24px;
  transition: all 0.3s ease;
}

.action-buttons .el-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.scanned-books {
  margin-top: 24px;
  padding: 16px;
  background: #ffffff;
  border-radius: 8px;
}

.scanned-books h4 {
  margin-bottom: 16px;
  color: #2c3e50;
  font-size: 16px;
  font-weight: 600;
}

.reader-info .info-content {
  padding: 16px;
}

.reader-info .info-content p {
  margin: 12px 0;
  font-size: 15px;
  line-height: 1.6;
}

.reader-info .info-content label {
  display: inline-block;
  width: 70px;
  color: #606266;
  font-weight: 500;
}

.start-scan-button {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 300px;
  background: rgba(255, 255, 255, 0.6);
  border-radius: 12px;
}

.cancel-scan {
  margin-top: 16px;
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(4px);
}

.el-table {
  border-radius: 8px;
  overflow: hidden;
  margin: 12px 0;
}

.delete-btn {
  padding: 8px;
  font-size: 18px;
  transition: all 0.3s ease;
}

.delete-btn:hover {
  background-color: #fef0f0;
  color: #f56c6c;
}

.action-footer {
  margin-top: 24px;
  text-align: right;
  padding-top: 16px;
  border-top: 1px solid #ebeef5;
}

.el-tag {
  font-size: 14px;
  height: 28px;
  line-height: 28px;
  padding: 0 12px;
  border-radius: 14px;
}

.back-button {
  background-color: #f56c6c;
  border-color: #f56c6c;
  font-weight: bold;
  min-width: 160px;
}

.back-button:hover {
  background-color: #ff7875;
  border-color: #ff7875;
}

@media screen and (max-width: 768px) {
  .borrow-container {
    padding: 10px;
  }

  .action-buttons {
    flex-direction: column;
    gap: 16px;
  }

  .action-buttons .el-button {
    width: 100%;
  }
}
</style>
